package com.ben.utils.device

import android.Manifest
import android.app.ActivityManager
import android.content.Context
import android.content.pm.PackageManager
import android.net.wifi.WifiManager
import android.os.Build
import androidx.core.app.ActivityCompat

/**
 * @author bin.yang
 * @date 2019/6/4
 * @maintainer bin.yang
 * @copyright 2019 Inc. All rights reserved.
 * @desc:
 */
object DeviceUtils {

    /**
     * 获取无线mac地址
     */
    @JvmStatic
    fun getWifiMac(context: Context): String? {
        val wifiManager =
            context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
        val connectionInfo = wifiManager?.connectionInfo
        return if (ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return connectionInfo?.macAddress
        } else null
    }

    private fun convertToMac(mac: ByteArray): String {
        val sb = StringBuilder()
        for (i in mac.indices) {
            sb.append(String.format("%02x", mac[i]))
            if (i != mac.size - 1) {
                sb.append(":")
            }
        }
        return sb.toString()
    }

    /**
     * 获取PID
     */
    @JvmStatic
    fun getPid(): Int {
        return android.os.Process.myPid()
    }

    /**
     * 获取系统版本
     */
    @JvmStatic
    fun getSystemVersion(): String? {
        return Build.VERSION.INCREMENTAL
    }

    /**
     * 获取android当前可用内存大小
     */
    @JvmStatic
    fun getAvailMemory(context: Context): Long {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)
        return memoryInfo.availMem / (1024 * 1024)
    }
}
